#include<stdlib.h>
#include<unistd.h>
#include"admin.h"
#include"tools.h"
#include"struct.h"
#include"dao.h"
#include"teacher.h"
extern List* tch_list;
extern void printf_tch(void* p);
extern int compare_tch(void*p1, void*p2);
//管理员登录
void admin_login(void)
{
	char user[20] = {};
	printf("请输入管理员用户名：");
	gets(user);
	char pass[7] = {};
	printf("请输入密码：");
	gets(pass);
	FILE *fwp = fopen("./data/admin.dat","r+");
	char pass2[7] = {};
	fread(pass2,sizeof(char),7,fwp);
//	printf("pass2: %s\n",pass2);
/*	if(0 == strcmp(pass2,"123456"))
	{
		puts("首次登录，请修改您的密码：");
		rewind(fwp);
		char pass3[7] = {};
		gets(pass3);
		fwrite(pass3,sizeof(char),7,fwp);
		fclose(fwp);
		return ;
	}
*/
	while(0 != strcmp(user,"admin") || 0 != strcmp(pass,pass2))
	{
		puts("用户名或者密码错误！\n");
		printf("请输入管理员用户名：");
		gets(user);
		printf("请输入密码：");
		gets(pass);
	}
	fclose(fwp);
	puts("登陆成功！\n");
	sleep(1);
	admin_menu();
}
//重置管理员密码
void reset_ad_pass(void)
{
	FILE* fwp = fopen("./data/admin.dat","w+");
	char pass[7] = {};
	printf("请输入您的新密码：");
	gets(pass);
	fwrite(pass,sizeof(char),7,fwp);
	fclose(fwp);
	puts("密码重置成功！");
}
//重置教师密码
void reset_tch_pass(void)
{
	Teacher* tch  = malloc(sizeof(Teacher));
	printf("请输入要重置教师密码的id:");
	scanf("%d",&tch->id);
	Node* node = find_node(tch_list,tch,compare_tch);
	if(NULL != node)
	{
		Teacher* tch1 = node->ptr;
		char pass[7] = {};
		printf("请输入该教师的新密码：");
		scanf("%s",pass);
		strcpy(tch1->pass,pass);
	}
	printf("修改成功！\n");
	sleep(2);

}
//添加教师
void add_tch(void)
{

	Teacher* tch = malloc(sizeof(Teacher));
	printf("请输入要添加的教师名：");
	gets(tch->name);
	printf("请输入性别：");
	scanf("%c",&tch->sex);
	FILE* frp = fopen("./data/teacher_id.dat","r+");
	fread(&tch->id,sizeof(int),1,frp);
	int id = tch->id+1;
	printf("%d\n",id);
	rewind(frp);
	fwrite(&id,sizeof(int),1,frp);
	fclose(frp);
	printf("请输入该教师的密码:");
	scanf("%s",tch->pass);
	add_head(tch_list,tch);
	printf("添加成功！\n");
	save_data(tch_list,"./data/teacher.dat",sizeof(Teacher));
	sleep(1);
}
//删除教师
void del_tch(void)
{
	Teacher* tch = malloc(sizeof(Teacher));
	printf("请输入要删除的教师id:");
	scanf("%d",&tch->id);
	if(del_node(tch_list,tch,compare_tch))
		printf("删除成功！\n");
	else printf("教师不存在，删除失败！\n");
	
}
//显示所有教师
void show_tch(void)
{
	show(tch_list,printf_tch);
	anykey_continue();
}
//管理员菜单
void admin_menu(void)
{
	for(;;)
	{
		system("clear");
		printf("*******admin********\n");
		puts("1、重置密码");
		puts("2、重置教师密码");
		puts("3、添加教师");
		puts("4、删除教师");
		puts("5、显示所有教师");
		puts("6、退出管理员系统");
		switch(get_cmd('1','6'))
		{
			case '1': reset_ad_pass();break;
			case '2': reset_tch_pass();break;
			case '3': add_tch();break;
			case '4': del_tch();break;
			case '5': show_tch();break;
			case '6': return ;
		}
	}
}

